package com.pzhuweb.sgblog.handler.security;

import com.alibaba.fastjson.JSON;
import com.pzhuweb.sgblog.domain.enums.AppHttpCodeEnum;
import com.pzhuweb.sgblog.domain.utils.ResponseResult;
import com.pzhuweb.sgblog.domain.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 鄧浩奇
 * @classname AuthenticationEntryPointImpl
 * @description
 * @date 2023/6/9 19:44
 **/



/*
 * 认证失败处理
 * */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        ResponseResult<?> result = null;
        authException.printStackTrace();
        if (authException instanceof InsufficientAuthenticationException) {
            result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR, "请先登陆");
        } else if (authException instanceof BadCredentialsException) {
            result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR, "用户名或密码错误");
        } else result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR);

        // 响应前端
        WebUtils.renderString(response, JSON.toJSONString(result));
    }
}
